/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package de.adorsys.ohos.securestoragelibrary;

import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;

/**
 * IOUtils
 *
 * @since 2021-05-19
 */
public class IoUtils {
    private static IoUtils instance = null;
    private static final int NEGATIVE_ONE = -1;
    private static final int UNIT = 1024;

    private IoUtils() {
    }

    /**
     * 静态锁对象
     *
     * @return Utils
     */
    public static synchronized IoUtils getInstance() {
        if (instance == null) {
            instance = new IoUtils();
        }
        return instance;
    }

    /**
     * writeFile
     *
     * @param data
     * @param file
     * @throws IOException
     */
    public static void writeFile(String data, File file) throws IOException {
        OutputStreamWriter out = null;
        try {
            out = new OutputStreamWriter(new FileOutputStream(file),"UTF-8");
            out.write(data);
            out.flush();
        } finally {
            close(out);
        }
    }

    /**
     * readFile
     *
     * @param file
     * @return String
     * @throws IOException
     */
    public static String readFile(File file) throws IOException {
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = new FileInputStream(file);
            out = new ByteArrayOutputStream();
            byte[] buf = new byte[UNIT];
            int len = NEGATIVE_ONE;
            while ((len = in.read(buf)) != NEGATIVE_ONE) {
                out.write(buf, 0, len);
            }
            out.flush();
            byte[] data = out.toByteArray();
            return new String(data);
        } finally {
            close(in);
            close(out);
        }
    }

    private static void close(Closeable c) {
        if (c != null) {
            try {
                c.close();
            } catch (IOException e) {
                // nothing
            }
        }
    }
}
